import tkinter as tk
from tkinter import colorchooser, Canvas
import pyautogui
import threading
class ColorTools:
    colorFlag = False  # 实时获取颜色开关
    def __init__(self, window):
        self.window = window
        self.R = tk.IntVar(value=0)
        self.G = tk.IntVar(value=0)
        self.B = tk.IntVar(value=0)
        self.HEX = tk.StringVar(value='')
        self.canvas = Canvas(self.window, width=100, height=120, bg='#000')
        self.canvas.place(x=30, y=80)
        self.init()

    def init(self):
        tk.Label(self.window, text="颜色选择器", font=('', 16)).place(x=30, y=50)
        self.setR()
        self.setG()
        self.setB()
        self.setH()
        tk.Button(text='选择颜色', command=self.select_color).place(x=350, y=80)
        tk.Button(text='拾取颜色', command=self.pick_color).place(x=350, y=170)

    def setR(self):
        tk.Label(self.window, text='R', font=('', 16)).place(x=150, y=80)
        tk.Entry(self.window, state='readonly', textvariable=self.R).place(x=190, y=85)
    def setG(self):
        tk.Label(self.window, text='G', font=('', 16)).place(x=150, y=115)
        tk.Entry(self.window, state='readonly', textvariable=self.G).place(x=190, y=120)

    def setB(self):
        tk.Label(self.window, text='B', font=('', 16)).place(x=150, y=150)
        tk.Entry(self.window, state='readonly', textvariable=self.B).place(x=190, y=155)

    def setH(self):
        tk.Label(self.window, text='HEX', font=('', 16)).place(x=150, y=185)
        tk.Entry(self.window, state='readonly', textvariable=self.HEX).place(x=190, y=190)

    def pick_color(self):
        ColorTools.colorFlag = True
        threading.Thread(target=self.get_color).start()
    def get_color(self):
        while ColorTools.colorFlag:
            x, y = pyautogui.position()
            screenImage = pyautogui.screenshot()
            color = screenImage.getpixel((x, y))
            hex_color = '#{:02x}{:02x}{:02x}'.format(color[0], color[1], color[2])
            self.R.set(color[0])
            self.G.set(color[1])
            self.B.set(color[2])
            self.HEX.set(hex_color)
            self.canvas.configure(background=self.HEX.get())


    def select_color(self):
        color = colorchooser.askcolor()
        if color:
            rgb = color[0]
            self.R.set(rgb[0])
            self.G.set(rgb[1])
            self.B.set(rgb[2])
            self.HEX.set(color[1])
            self.canvas.configure(background=color[1])